package com.ai.web.weixin;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import com.ai.web.cache.Constants;
import com.ai.web.http.HttpResponse;
import com.ai.web.http.HttpUtil;
import com.ai.web.util.JsonUtil;


public class WeixinContext {

	private static Logger logger = Logger.getLogger(WeixinContext.class);
	
	public static String access_token = "-UqBN7Bo-2lTlsNB6ibp-NhFnDWX0eU0I7eG1XIuqSsK4yB7vfCUPyWXToxaNKuD";
	
	private static int getTokenCount = 0;
	private static Timer timer = new Timer();
	private static TimerTask getTokenTask = getTokenTask();
	
	private static TimerTask getTokenTask() {
		return new TimerTask() {
		
			@Override
			public void run() {
				getAccessToken();			
			}
		};
	}
	
	public static void init() {
		getAccessToken();
		getMenu();
		getAccessToken();
	}
	
	
	public static void getMenu() {
		logger.info("getMenu start. token=" + access_token);
		String serviceUrl = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" + access_token;
	
		try {
			HttpResponse httpResponse = HttpUtil.httpRequest(serviceUrl, "GET", null, null);
			
			HashMap map = JsonUtil.fromJson(httpResponse.getBody(), HashMap.class);
			if (map == null || map.size() == 0) {
				// 没有menu，创建menu
				createMenu();
			} else {
				Object obj = map.get("errcode");
				if (obj != null) {
					logger.error("getMenu errcode=" + obj);
					// recreate menu
					createMenu();
				}
			}
			
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	public static void createMenu() {
		String serviceUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + access_token;
		
		try {
			URL fileUrl = Thread.currentThread().getContextClassLoader().getResource("menu.txt");
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileUrl.getFile()), "UTF-8"));
			String line = null;
			StringBuilder content = new StringBuilder();
			while ((line = br.readLine()) != null) {
				content.append(line);
			}
			br.close();
			
			logger.info("menu json:" + content);
	        
			HttpResponse httpResponse = HttpUtil.httpRequest(serviceUrl, "POST", null, content.toString());
			
			HashMap map = JsonUtil.fromJson(httpResponse.getBody(), HashMap.class);
			Object obj = map.get("errcode");
			if (obj != null) {
				logger.info("createMenu errcode=" + obj);
			}
			
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	public static void deleteMenu() {
		String serviceUrl = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token="+access_token;
		
		try {
			HttpResponse httpResponse = HttpUtil.httpRequest(serviceUrl, "GET", null, null);
			
			HashMap map = JsonUtil.fromJson(httpResponse.getBody(), HashMap.class);
			Object obj = map.get("errcode");
			if (obj != null) {
				logger.info("deleteMenu errcode=" + obj);
			}
			
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	public static void main(String[] args) {
		getAccessToken();
		deleteMenu();
		createMenu();
		
		getMenu();
		
		
//		String serviceUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+WeixinContext.access_token;
//		String body = "{\"touser\":\"o4HX-th-uVXOKbfwqeRS5AB77H2M\",\"msgtype\":\"text\",\"text\": {\"content\":\"您好,您的账号已经通过审核\"}}";
//    	logger.info("auditWxUser url:"+serviceUrl+"  body:"+body);
//    	System.out.println("auditWxUser url:"+serviceUrl+"  body:"+body);
//    	try {
//    		HttpResponse httpResponse = HttpUtil.httpRequest(serviceUrl, "POST", null, body);
//    		logger.info("[auditWxUser] message/custom/send: " + httpResponse.toString());
//    	} catch (Exception e) {
//			logger.error(e.getMessage(), e);
//		}
		
		
	}
	
	
	public static void getAccessToken() {
		
		logger.info("getAccessToken appid=" + Constants.APPID
				 	+ "  secret=" + Constants.SECRET);
		
		String serviceUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Constants.APPID
				 	+ "&secret=" + Constants.SECRET;
		
		try {
			HttpResponse httpResponse = HttpUtil.httpRequest(serviceUrl, "GET", null, null);
			
			HashMap map = JsonUtil.fromJson(httpResponse.getBody(), HashMap.class);
			Object obj = map.get("errcode");
			if (obj != null) {
				logger.error("getAccessToken errcode=" + obj + " retry:" + getTokenCount);
				if (getTokenCount < 5) {
					// 10秒后再次获取，重试5次
					if (getTokenTask != null) {
						getTokenTask.cancel();
						timer.purge();
						getTokenTask = getTokenTask();
					}
					timer.schedule(getTokenTask, 10 * 1000);
				}
			} else {
				getTokenCount = 0;
				access_token = map.get("access_token").toString();
				String expires = map.get("expires_in").toString();
				logger.info("currTime=" + new Date() 
					+ " access_token="  + access_token 
					+ " expires=" + expires);
				
				// 过期前再次去获取token
				if (getTokenTask != null) {
					getTokenTask.cancel();
					timer.purge();
					getTokenTask = getTokenTask();
				}
				timer.schedule(getTokenTask, (Long.parseLong(expires) - 200) * 1000);
			}
			
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
		}
		
	}
	
}
